package com.zx._12_算法.数据结构.tree;

import com.zx._12_算法.TreeNode;
import java.util.LinkedList;

/*
数据结构如下：
             1
        /         \
       2           7
    /    \       /    \
    3    5       8   9
   /      \
  4        6
 */
public class A5_逐层打印 {

    public static void main(String[] args) {
        TreeNode root = TreeNode.buildTree("1(2(3(4,),5(,6)),7(8,9))#");
        run1(root);
    }

    /**
     * 使用队列存储
     * @param root
     */
    private static void run1(TreeNode root) {

        LinkedList<TreeNode> list = new LinkedList();
        list.add(root);

        int floor = 0;

        while (!list.isEmpty()) {
            System.out.print("层级：" + floor + ": ");

            int size = list.size();
            for (int i = 0; i < size; i++) {
                // 移除并获得头部数据
                TreeNode node = list.poll();
                System.out.print(node.val + ",");

                if (node.left != null) {
                    list.add(node.left);
                }
                if (node.right != null) {
                    list.add(node.right);
                }
            }

            floor++;
            System.out.println();
        }
    }
}
